<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    .app {
      box-sizing: content-box;
      margin: 50px;
      width: 400px;
      height: 600px;
      border: 4px solid salmon;
      position: relative;
    }
    .snake {
      border: 1px solid skyblue;
    }
    .unit {
      position: absolute;
      width: 10px;
      height: 10px;
      background-color: royalblue;
    }
  </style>
</head>
<body>
  <div class="app">
  </div>

  <script>
    class Snake {
      units = []
      el = null
      direction = "R"  // "R", "L", "T", "B"

      init(container) {
        // 创建自己的dom并且挂载到容器
        const el = document.createElement("div")
        el.classList.add("snake")
        container.appendChild(el)
        this.el = el

        // 创建第一个单位
        new SnakeUnit(this)

        console.log(this)
        // 开启计时
        setTimeout(() => this.move(), 1000)
      }

      move() {
        let i = this.units.length
        while (i >= 0) {
          this.units[i].move()
          i--
        }
      }

    }

    class SnakeUnit {
      el = null
      parentInstance = null

      constructor(parent) {
        this.parentInstance = parent
        this.createHead()
      }

      createHead() {
        const unitEl = document.createElement("div")
        unitEl.classList.add("unit")

        this.el = unitEl
        this.parentInstance.el.appendChild(this.el)
        this.parentInstance.units.unshift(this)


        this.refreshPosition(unitEl)
      }

      move() {
        const isHead = this.parentInstance.units[0] === this
        if (isHead){  // 第一个单位根据方向
          switch (this.parentInstance.direction) {
            case "L":
              return this.el.style.left = parseInt(this.el.style.left) - 1 + "px"
            case "R":
              return this.el.style.left = parseInt(this.el.style.left) + 1 + "px"
            case "T":
              return this.el.style.top = parseInt(this.el.style.top) + 1 + "px"
            case "B":
              return this.el.style.top = parseInt(this.el.style.top) - 1 + "px"
          }
        }else{  // 其他单位,用前面一个单位的坐标
          this.refreshPosition(this.el)
        }
      }

      refreshPosition(el) {
        if (this.parentInstance.units.length) {
          el.style.left = "5px"
          el.style.top = "5px"
        } else {
          const list = this.parentInstance.units
          const lastUnit = list[list.length - 1]
          el.style.left = lastUnit.style.left
          el.style.top = lastUnit.style.top
        }
      }
    }


    new Snake().init(document.querySelector(".app"))
  </script>
</body>
</html>
